package org.sxf.app.sign.provider;

import com.lidroid.xutils.util.LogUtils;

import org.sxf.app.sign.data.DataCacheSingleton;
import org.sxf.service.demo.SignPrx;
import org.sxf.service.demo.SignPrxHelper;

import Ice.Communicator;

public class Client {

    interface CommunicatorCallback{
        void onWait();
        void onCreate(Ice.Communicator comm);
        void onError(Ice.LocalException ex);
    }

    private static boolean isInitialized;
    private static Ice.LocalException ex;
    private static CommunicatorCallback commCallback;
    private static Communicator communicator = null;

    private static SignPrx mpServicePrx;
    public static SignPrx getServicePrx(){
        if(mpServicePrx==null){
            mpServicePrx = createServicePrx();
        }
        return mpServicePrx;
    }
    private static SignPrx createServicePrx(){
        new Client();
        initializeCommunicator();//init client runtime

        Ice.ObjectPrx prx = communicator.stringToProxy(DataCacheSingleton.getInstance().getIceServerConfig()); //create the proxy
        return SignPrxHelper.uncheckedCast(prx);
    }


    private static void initializeCommunicator(){
        try{
            Ice.Communicator comm;
            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = Ice.Util.createProperties();
            initData.properties.setProperty("Ice.Trace.Network", "3");
            comm = Ice.Util.initialize(initData);
            communicator = comm;
            if(commCallback != null){
                commCallback.onCreate(communicator);
            }
            isInitialized = true;
        }catch(Ice.LocalException e){
            if(commCallback != null){
                commCallback.onError(e);
            }
            ex = e;
            isInitialized = true;
        }
    }


    public static void clearPrx(){
        destroyConnection();
        commCallback = null;
        communicator = null;
        mpServicePrx = null;

    }


    public void setCommunicatorCallback(CommunicatorCallback cb){
        if(isInitialized){
            if(ex!=null){
                cb.onError(ex);
            }
            else{
                cb.onCreate(communicator);
            }
        }
        else{
            commCallback = cb;
            commCallback.onWait();
        }
    }

    public static void destroyConnection(){
        if(communicator != null){
            try{
                communicator.destroy();
            }catch(Ice.LocalException e){}
        }
    }
}
